package com.example.onlinemonitoring.autoRun;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DatabaseBackupTask {

    @Scheduled(cron = "0 0 0 * * 1") // 每周一凌晨执行备份任务
    // @Scheduled(cron = "0 * * * * *") // 每周一凌晨执行备份任务
    public void backupDatabase() throws IOException {

        long requiredSpace = 100 * 1024 * 1024 * 1024; // 100GB
        long availableSpace = getAvailableDiskSpace();

        if (availableSpace < requiredSpace) {
            System.out.println("磁盘空间不足，无法执行备份任务。");
            return;
        }
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = "backup_" + timestamp + ".sql";
        String command = "mysqldump -u root -password=rixin transformer_substation > " + fileName;
        Runtime.getRuntime().exec(command);
        System.out.println("开始执行备份任务。");
    }

    private long getAvailableDiskSpace() throws IOException {
        Path path = FileSystems.getDefault().getPath("/");
        FileStore store = Files.getFileStore(path);
        return store.getUsableSpace();
    }
}
